package team.wuyou.util.annotation.log;


import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import team.wuyou.util.HttpSessionUtil.IPUtil;
import team.wuyou.util.HttpSessionUtil.UserSessionUtil;
import team.wuyou.util.HttpSessionUtil.UuidUtil;
import team.wuyou.util.annotation.log.bean.ExceptionLog;
import team.wuyou.util.annotation.log.bean.OperationLog;
import team.wuyou.util.annotation.log.service.ExceptionLogService;
import team.wuyou.util.annotation.log.service.OperationLogService;


import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @Description //切面处理类，操作日志异常日志记录处理
* @Date 2024/1/6 14:01
* @Wang
*
**/
@Aspect
@Component
public class OperLogAspect {
    @Value("${version}")
    private String operVer;

    @Autowired
    private OperationLogService operationLogService;

    @Autowired
    private ExceptionLogService exceptionLogService;

    @Pointcut("@annotation(team.wuyou.util.annotation.log.OperLog)")
    public void operLogPoinCut() {
    }

    @Pointcut("execution(* team.wuyou.controller..*.*(..))")
    public void operExceptionLogPoinCut() {
    }

    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        // 获取 RequestAttributes 的逻辑
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=null;
        if (requestAttributes != null) {
            request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

            if (request == null) {
                // 如果 resolveReference 返回 null，手动创建 HttpServletRequest
                request = createHttpServletRequest();

                // 设置 HttpServletRequest 到 RequestAttributes
                requestAttributes.setAttribute(RequestAttributes.REFERENCE_REQUEST, request, RequestAttributes.SCOPE_REQUEST);
            }

            // 其他逻辑...
        } else {
            // 处理 requestAttributes 为 null 的情况...
            System.out.println("RequestAttributes==null");
            // 如果为 null，手动创建 ServletRequestAttributes
            HttpServletRequest mockRequest =createHttpServletRequest();/* 创建一个模拟的 HttpServletRequest */;
            requestAttributes = new ServletRequestAttributes(mockRequest);

            // 将创建的 RequestAttributes 设置为当前线程的 RequestAttributes
            RequestContextHolder.setRequestAttributes(requestAttributes);
        }
        OperationLog operlog = new OperationLog();
        try {
            operlog.setOperId(UuidUtil.get32UUID());
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            OperLog opLog = method.getAnnotation(OperLog.class);
            if (opLog != null) {
                String operModul = opLog.operModul();
                String operType = opLog.operType();
                String operDesc = opLog.operDesc();
                operlog.setOperModul(operModul);
                operlog.setOperType(operType);
                operlog.setOperDesc(operDesc);
            }

            String className = joinPoint.getTarget().getClass().getName();
            String methodName = method.getName();
            methodName = className + "." + methodName;

            operlog.setOperMethod(methodName);

            Map<String, String> rtnMap = converMap(request.getParameterMap());
            String params = JSON.toJSONString(rtnMap);

            operlog.setOperRequParam(params);
            operlog.setOperRespParam(JSON.toJSONString(keys));
            operlog.setOperUserName(UserSessionUtil.getCurrentUserName(request));
            operlog.setOperIp(IPUtil.getRemortIP(request));
            operlog.setOperUri(request.getRequestURI());
            operlog.setOperCreateTime(new Date());
            operlog.setOperVer(operVer);

            operationLogService.insert(operlog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        // 获取 RequestAttributes 的逻辑
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=null;
        if (requestAttributes != null) {
            request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

            if (request == null) {
                // 如果 resolveReference 返回 null，手动创建 HttpServletRequest
                request = createHttpServletRequest();

                // 设置 HttpServletRequest 到 RequestAttributes
                requestAttributes.setAttribute(RequestAttributes.REFERENCE_REQUEST, request, RequestAttributes.SCOPE_REQUEST);
            }

            // 其他逻辑...
        } else {
            // 处理 requestAttributes 为 null 的情况...
            System.out.println("RequestAttributes==null");
            // 如果为 null，手动创建 ServletRequestAttributes
            HttpServletRequest mockRequest =createHttpServletRequest();/* 创建一个模拟的 HttpServletRequest */;
            requestAttributes = new ServletRequestAttributes(mockRequest);

            // 将创建的 RequestAttributes 设置为当前线程的 RequestAttributes
            RequestContextHolder.setRequestAttributes(requestAttributes);
        }
        ExceptionLog excepLog = new ExceptionLog();
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            excepLog.setExcId(UuidUtil.get32UUID());

            String className = joinPoint.getTarget().getClass().getName();
            String methodName = method.getName();
            methodName = className + "." + methodName;

            Map<String, String> rtnMap = converMap(request.getParameterMap());
            String params = JSON.toJSONString(rtnMap);
            excepLog.setExcRequParam(params);
            excepLog.setOperMethod(methodName);
            excepLog.setExcName(e.getClass().getName());
            excepLog.setExcMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));
            excepLog.setOperUserName(UserSessionUtil.getCurrentUserName(request));
            excepLog.setOperUri(request.getRequestURI());
            excepLog.setOperIp(IPUtil.getRemortIP(request));
            excepLog.setOperVer(operVer);
            excepLog.setOperCreateTime(new Date());

            exceptionLogService.insert(excepLog);

        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }

    // 创建 HttpServletRequest 对象的示例方法
    private HttpServletRequest createHttpServletRequest() {
        MockHttpServletRequest mockRequest = new MockHttpServletRequest();
        // 设置请求方法、请求路径等信息
        mockRequest.setMethod("POST");
        mockRequest.setRequestURI("/example-path");
        mockRequest.setAttribute("username","test");
        // 模拟设置请求参数
        Map<String, String[]> parameterMap = new HashMap<>();
        parameterMap.put("param1", new String[]{"value1"});
        parameterMap.put("param2", new String[]{"value2"});
        mockRequest.setParameters(parameterMap);
        // 其他设置...
        return mockRequest;
    }

    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuilder strbuff = new StringBuilder();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet).append("\n");
        }
        return exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
    }
}
